<template>
    <div id="sell">

        <el-form :inline="true" class="demo-form-inline"  style="transform: scale(2);margin-top: 30px;margin-left: 50%">
            <el-form-item :label="$t('数量')">
                <el-input type="number" :placeholder="$t('商品编码')" v-model="number" autocomplete="off" style="width: 80px"></el-input>
            </el-form-item>

            <el-form-item :label="$t('商品编码')" v-if="inputModel === 1" >
                <el-input :placeholder="$t('商品编码')" v-model="code"  autocomplete="off" @keydown.native.enter="add" style="float: left;width: 100px" ref="codeInput"></el-input>
                <el-button icon="el-icon-sort" @click="inputModel = 2" style="float: left"></el-button>
            </el-form-item>

            <el-form-item :label="$t('商品名称')" v-if="inputModel === 2" >
                <el-select v-model="searchResult" filterable :placeholder="$t('请选择')" style="width: 100px">
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
                <el-button  icon="el-icon-sort" @click="inputModel = 1"></el-button>
            </el-form-item>

<!--            <el-form-item>-->
<!--                <div class="info">-->
<!--                    <span class="text">{{ $t('商品') }}:</span>-->
<!--                    <span class="price">{{ sumPrice }}</span>-->
<!--                    <span class="text">{{ $t('税费') }}:</span>-->
<!--                    <span class="price">{{ sumTax }}</span>-->
<!--                    <span class="text">{{ $t('总计') }}:</span>-->
<!--                    <span class="price">{{ total }}</span>-->
<!--                    <span class="text">{{ $t('现金') }}:</span>-->
<!--                    <input class="price" style="width: 100px;" type="number" v-model="cash" >-->
<!--                    <span class="text">{{ $t('找零') }}:</span>-->
<!--                    <span class="price">{{ (cash - total).toFixed(2) }}</span>-->

<!--                    <el-button size="small" round type="primary" @click="save">{{ $t('结算') }}</el-button>-->
<!--                    <el-button round type="danger" size="small"  @click="delAll()" >{{ $t('全部删除') }}</el-button>-->
<!--                </div>-->

<!--            </el-form-item>-->

        </el-form>


        <div id="cartList">

            <table class="matable" style="user-select: none;">
                <tr>
                    <td>{{ $t('行数') }}</td>
                    <td>{{ $t('商品名称') }}</td>
                    <td>{{ $t('数量') }}</td>
                    <td>{{ $t('价格') }}</td>
                    <td>{{ $t('税费') }}</td>
                    <td>{{ $t('总计') }}</td>
                    <td>{{ $t('操作') }}</td>
                </tr>
                <tr v-for="(item,index) in cartList" v-bind:key="item.id">
                    <td>{{ index }}</td>
                    <td>{{ item.name}}</td>
                    <td>{{ item.number }}</td>
                    <td>{{ item.price }}</td>
                    <td>{{ item.tax }}</td>
                    <td>{{ ((item.price+item.tax)*item.number).toFixed(2) }}</td>
                    <td><el-button size="mini" round type="danger" @click="del(item,index)">{{ $t('删除') }}</el-button></td>
                </tr>
            </table>
        </div>

        <div id="bottom">
            <div>
                <span class="text">{{ $t('商品') }}:</span>
                <span class="price">{{ sumPrice }}</span>
                <span class="text">{{ $t('税费') }}:</span>
                <span class="price">{{ sumTax }}</span>
                <span class="text">{{ $t('总计') }}:</span>
                <span class="price">{{ total }}</span>
            </div>

            <div>
                <span class="text">{{ $t('现金') }}:</span>
                <input class="price" style="width: 100px;" type="number" v-model="cash" >
                <span class="text">{{ $t('找零') }}:</span>
                <span class="price">{{ (cash - total).toFixed(2) }}</span>

                <el-button round type="primary" @click="save">{{ $t('结算') }}</el-button>
                <el-button round type="danger" @click="delAll()" >{{ $t('全部删除') }}</el-button>
            </div>

        </div>

        <div id="alert" v-if="inputErrorShow">
            {{ $t('录入失败') }}

            <el-button  @click="inputErrorShow=false;">{{ $t('关闭') }}</el-button>
        </div>
    </div>
</template>

<script>

import {ipcRenderer} from "electron";

export default {
    name: "sell",
    data(){
        return{
            inputErrorShow:false,
            searchResult:"",
            inputModel:1,
            cash:"",
            number:1.00,
            code:"",
            cartList:[],
            options: [{
                value: '黄金糕',
                label: '黄金糕'
            }, {
                value: '双皮奶',
                label: '双皮奶'
            }, {
                value: '蚵仔煎',
                label: '蚵仔煎'
            }, {
                value: '龙须面',
                label: '龙须面'
            }, {
                value: '北京烤鸭',
                label: '北京烤鸭'
            }]
        }
    },
    computed:{

        sumPrice(){
            return this.cartList.reduce((acc, item) => {
                return acc + (item.number * item.price);
            }, 0).toFixed(2);
        },
        sumTax(){
            return this.cartList.reduce((acc, item) => {
                return acc + (item.number * item.tax);
            }, 0).toFixed(2);
        },
        total(){
            return this.cartList.reduce((acc, item) => {
                return acc + (item.number * (item.tax+item.price));
            }, 0).toFixed(2);
        }
    },
    watch:{
        searchResult(val){
            if (val === ""){
                return;
            }
            const cart = {
                number: this.number,
                code: this.code,
                name:val,
                price:this.rand(1000,10000)/100,
                tax:this.rand(200,1000)/100,
            };
            this.cartList.push(JSON.parse(JSON.stringify(cart)));
            this.number = 1;
            this.code = "";
            this.searchResult = "";
            this.inputModel = 1;

            // ipcRenderer.send('tts-play', this.$t('录入成功'));
            console.log(val);
        },
        number(val){
            if (val == ""){
                this.number = 1;
            }
        }
    },
    methods:{
        delAll(){
            if (this.cartList.length == 0){
                return;
            }
            this.$prompt( this.$t('请输入店长密码或等待店长远程确认'), this.$t('提示'),
                {
                    type:"warning",            // 图标样式 "warning"|"error"...
                    inputValue: '',
                    inputErrorMessage: this.$t('输入不能为空'),
                    inputValidator: (value) => {       // 点击按钮时，对文本框里面的值进行验证
                        if(!value) {
                            return this.$t('输入不能为空');
                        }
                    }
                }).then(({value}) => {

                if (value != "111111"){
                    this.$alert(this.$t('密码错误'),this.$t('提示'),{
                        type:"error"
                    });
                }else{
                    this.reset();
                    this.$alert(this.$t('操作成功'),this.$t('提示'),{
                        type:"success"
                    });
                }
                // TO DO DO ...
            }).catch((err) => {
                console.log(err);
            });
        },
        del(item,index){
            this.$prompt( this.$t('请输入店长密码或等待店长远程确认'), this.$t('提示'),
                {
                    type:"warning",            // 图标样式 "warning"|"error"...
                    inputValue: '',
                    inputErrorMessage: this.$t('输入不能为空'),
                    inputValidator: (value) => {       // 点击按钮时，对文本框里面的值进行验证
                        if(!value) {
                            return this.$t('输入不能为空');
                        }
                    }
                }).then(({value}) => {

                if (value != "111111"){
                    this.$alert(this.$t('密码错误'),this.$t('提示'),{
                        type:"error"
                    });
                }else{
                    this.cartList = [];
                    this.$alert(this.$t('操作成功'),this.$t('提示'),{
                        type:"success"
                    });
                }
                // TO DO DO ...
            }).catch((err) => {
                console.log(err);
            });
        },
        save(){
            if (this.$route.path == "/buy/index"){
                this.$prompt( this.$t('请填写出银说明'), this.$t('提示'),
                    {
                        type:"warning",            // 图标样式 "warning"|"error"...
                        inputValue: '',
                        inputErrorMessage: this.$t('输入不能为空'),
                        inputValidator: (value) => {       // 点击按钮时，对文本框里面的值进行验证
                            if(!value) {
                                return this.$t('输入不能为空');
                            }
                        }
                    }).then(({value}) => {

                    this.print();
                    this.reset();
                    // TO DO DO ...
                }).catch((err) => {
                    console.log(err);
                });
            }else{

                this.print();
                this.reset();
            }

        },
        reset(){
            this.cartList = [];
            this.cash = 0;
            this.number = 1.00;
            this.code = "";
        },
        onKeyDown(e) {
            if (e.keyCode === 13) {
                this.add() // 触发了回车/空格键
            }
        },
        add(){
            if (this.code === ""){
                ipcRenderer.send('tts-play', this.$t('录入失败'));
                var that = this;
                setTimeout(function (){
                    that.inputErrorShow = true;
                    that.$refs.codeInput.blur();
                    // that.$alert(that.$t('录入失败'),that.$t('提示'),{
                    //     type:"error"
                    // });
                },0)

                return;
            }

            const cart = {
                number: this.number,
                code: this.code,
                name:"测试商品名称",
                price:this.rand(1000,10000)/100,
                tax:this.rand(200,1000)/100,
            };
            this.cartList.push(JSON.parse(JSON.stringify(cart)));
            this.number = 1;
            this.code = "";

            // ipcRenderer.send('tts-play', this.$t('录入成功'));

        },
        print(){
            // In the main process
            // or in render process
            // const {PosPrinter} = require('electron').remote.require("electron-pos-printer");

            // each object in the data array accounts for a row or line
            const data = [
                {type: 'text', value: 'TEST text',style: {fontWeight: "700", textAlign: 'center', fontSize: "24px"}},
                {type: 'text', value: 'TEST text',style: {fontWeight: "700", textAlign: 'center', fontSize: "22px"}},
                {type: 'text', value: '中文测试',style: {fontWeight: "700", textAlign: 'center', fontSize: "20px"}},
                {type: 'text', value: '中文测试',style: {fontWeight: "700", textAlign: 'center', fontSize: "18px"}},
                {type: 'text', value: '中文测试',style: {fontWeight: "700", textAlign: 'center', fontSize: "16px"}},
                {type: 'text', value: 'TEST text',style: {fontWeight: "700", textAlign: 'center', fontSize: "14px"}},
                {type: 'text', value: 'TEST text',style: {fontWeight: "700", textAlign: 'center', fontSize: "12px"}},
                {type: 'text', value: 'TEST text',style: {fontWeight: "700", textAlign: 'center', fontSize: "10px"}},
                {type: 'text', value: 'TEST text',style: {fontWeight: "700", textAlign: 'center', fontSize: "8px"}},
                {type: 'text', value: '中文测试',style: {fontWeight: "700", textAlign: 'center', fontSize: "6px"}},
                {type: 'text', value: '中文测试',style: {fontWeight: "700", textAlign: 'center', fontSize: "4px"}},
                {type: 'text', value: '中文测试',style: {fontWeight: "700", textAlign: 'center', fontSize: "2px"}}
            ];

            ipcRenderer.send('print', {
                data:data,
                printer:localStorage.printer
            });


            //
            //
            // const options = {
            //     preview: false,               // Preview in window or print
            //     width: '170px',               //  width of content body
            //     margin: '0 0 0 0',            // margin of content body
            //     copies: 1,                    // Number of copies to print
            //     printerName: 'ImpresoraBarata',        // printerName: string, check with webContent.getPrinters()
            //     //printerName: 'EPSON TM-T88V Receipt',        // printerName: string, check with webContent.getPrinters()
            //     timeOutPerLine: 400,
            //     pageSize: { height: 301000, width: 71000 },  // page size
            //     silent: true
            // }
            //
            // PosPrinter.print(data, options)
            // .then(() => { })
            // .catch((error) => {
            //     console.error(error);
            // });

            // try {
            //     await PosPrinter.print(data, options);
            //     console.log("Impresión exitosa");
            // } catch (error) {
            //     console.error("Error al imprimir:", error);
            // }


        }
    },
    mounted() {
        // window.addEventListener('keydown', this.onKeyDown, true) //开启监听键盘按下事件

    },
    destroyed() {
        // window.removeEventListener('keydown',this.onKeyDown, true);
    }
}
</script>

<style lang="scss">
    #sell{
        height: 100%;padding: 10px; background: #f3f3f3;position: relative; overflow: hidden;

        #cartList{
            max-height: calc( 100% - 220px );
            overflow-y: auto; font-size: 30px;
        }

        .info{

            .text{

            }
            .price{
                font-size: x-large; margin-right: 20px;color: orangered;
            }
        }

        #bottom{
            display: flex; justify-content:center;
            position: absolute;
            bottom: 0;
            padding:0 20px ;background: #FFF; width: calc( 100% - 20px);
            height: 100px;line-height: 100px; font-size: 30px;

            .text{

            }
            .price{
                font-size:50px; margin-right: 20px;color: orangered;
            }
        }

        #alert{
            position: absolute; top: 0;left: 0;width: 100%;height: 100%; display: flex;
            background: #FFFFFF; color:red; font-size: 200px; justify-content: center;align-items: center;
        }
    }
</style>
